<template>
    <div>
        <el-card style="max-width: 100%">
            <el-header class="header">
                <el-space wrap :size="size">
                    <el-select placeholder="游戏查询:" v-model="value2" multiple collapse-tags filterable
                               style="width: 240px">
                        <el-option v-for="item in gemas_list" :key="item" :label="item.name" :value="item.appid"/>
                    </el-select>
                    <el-button @click="Game_Find" class="button" type="success">
                        <el-icon>
                            <Search/>
                        </el-icon>
                        游戏查询
                    </el-button>
                    <el-button @click="Realtime" class="button" type="success">
                        <el-icon>
                            <el-icon>
                                <Clock/>
                            </el-icon>
                        </el-icon>
                        实时数据
                    </el-button>

                    <el-button @click="resetting" class="button" type="success">
                        <el-icon>
                            <RefreshLeft/>
                        </el-icon>
                        页面刷新
                    </el-button>
                    ECPM:{{ getEcpm(amount)}}￥
                    <div>
                        总收入:{{ getLastTwoDigitsAfterDivision(average) }}￥
                    </div>
                </el-space>
                <!-- <el-button @click="addGame" class="button" type="success"> <el-icon>
                <Plus />
            </el-icon>添加</el-button> -->

            </el-header>
            <el-header class="header">
                <div class="block">
                    <span class="demonstration">日期时间查询</span>
                    <el-date-picker v-model="value1" type="datetimerange" start-placeholder="开始时间"
                                    end-placeholder="结束时间" :default-time="defaultTime1"/>
                    <el-button type="primary" plain style="margin-left: 10px;" @click="find_getitem(1)">
                        获取昨天的数据
                    </el-button>
                    <el-button type="primary" plain @click="find_getitem(3)">获取三天前的数据</el-button>
                    <el-button type="primary" plain @click="find_getitem(7)">获取七天前的数据</el-button>
                </div>
            </el-header>
            <el-table :data="arrlist" stripe style="width: 100%;height: 460px;" v-loading="loading">
                <el-table-column prop="cost" label="cost" align="center">
                    <template #default="scope">
                        {{ getLastTwoDigitsAfterDivision(scope.row.cost) }}￥
                    </template>
                </el-table-column>
                <el-table-column prop="event_name" label="geams_name" align="center">
                    <template #default="scope">
                        <span>{{ scope.row.name }}
                            <el-tooltip class="box-item" effect="dark" content="点击可以复制" placement="top-start">
                                <span @click="copy_appid(scope.row.name)"><el-icon class="icon_color">
                                        <CopyDocument/>
                                    </el-icon></span>
                            </el-tooltip>
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="event_time" label="event_time" align="center">
                    <template #default="scope">
                        {{ dateToString(new Date(scope.row.event_time)) }}
                    </template>
                </el-table-column>
                <el-table-column prop="open_id" label="open_id" align="center">
                    <template #default="scope">
                        <span>{{ scope.row.open_id }}
                            <el-tooltip class="box-item" effect="dark" content="点击可以复制" placement="top-start">
                                <span @click="copy_appid(scope.row.open_id)"><el-icon class="icon_color">
                                        <CopyDocument/>
                                    </el-icon></span>
                            </el-tooltip>
                        </span>
                    </template>
                </el-table-column>
            </el-table>
            <div>
                <el-main>
                    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                                   :current-page="currentPage" :page-size="pageSize"
                                   layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
                </el-main>
            </div>

            <!-- 添加游戏弹出宽 -->
            <el-dialog v-model="dialogFormVisible" title="游戏信息添加" width="500">
                <el-form ref="ruleFormRef" style="max-width: 600px" :model="form" status-icon :rules="rules"
                         label-width="auto" class="demo-ruleForm">
                    <el-form-item label=" Game Aid" prop="aid">
                        <el-input v-model="form.aid" type="text" autocomplete="off"/>
                    </el-form-item>
                    <el-form-item label="Game cost" prop="cost">
                        <el-input v-model.number="form.cost" type="text"/>
                    </el-form-item>
                    <el-form-item label="Game did" prop="did">
                        <el-input v-model="form.did"/>
                    </el-form-item>
                    <el-form-item label="games_name" prop="event_name">
                        <el-input v-model="form.event_name"/>
                    </el-form-item>
                    <el-form-item label="Event_item" prop="event_time">
                        <el-col :span="11">
                            <el-date-picker v-model="form.event_time" type="date" placeholder="Pick a date"
                                            style="width: 100%"/>
                        </el-col>
                    </el-form-item>
                    <el-form-item label="open_id" prop="open_id">
                        <el-input v-model="form.open_id"/>
                    </el-form-item>
                    <el-form-item label="id" prop="id">
                        <el-input v-model="form.id"/>
                    </el-form-item>
                    <el-form-item label="App_id" prop="id">
                        <el-input v-model="form.appid"/>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="dialogFormVisible = false">取消</el-button>
                        <el-button type="primary" @click="submitForm(ruleFormRef)">
                            确定
                        </el-button>
                    </div>
                </template>
            </el-dialog>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import replication from '../../hooks/copy_text'//一键复制文本
import {GameEcpmlist, GameEcpmAdd, getGames} from '@/request/api'// 封装的请求接口S
import {ref, onMounted, reactive, watch} from 'vue'
import {Stoer_Game_lits} from '@/store/store_game_list'
import type {Guers, userinfo} from '@/type/infolist'//自定义ts
import {Stoer_Game_expm} from '@/store/store_games_expm'
import {dateToString, getEcpm} from '../../utools/index';
import {type FormInstance, type FormRules, ElMessage} from 'element-plus'
import {getLastTwoDigitsAfterDivision, isBetween} from "@/utools";
//表单验证
let arrlist = ref<Guers[]>([])
let dialogFormVisible = ref(false)
let value2 = ref<string[]>([])//游戏名称查询
let currentPage = ref(1)
let value1 = ref([])
const total = ref<number>(10);
const pageSize = ref<number>(10);
let amount = ref<number>(0)
let gemas_list = ref<userinfo[]>([])
let page_list = ref<Guers[]>([])
let size = ref<number>(20)
let average = ref<number>(0)
let page_length = ref<Guers[]>([])
let page_size = ref<number>(0)
let and = ref<number>(0)
let ecpm_list = ref<Guers[]>([])//最终表单
let length_size = ref<number>(0)

let loading = ref(true)
//游戏挂载
onMounted(() => {
    init()
})
let calendar_change = () => {
}
//时间选着器
let defaultTime1: [Date, Date] = [
    new Date(2000, 1, 1, 0, 0, 0),
    new Date(2000, 2, 1, 23, 59, 0),
]
//初始渲染
let init = async () => {
    try {
        let cost_sum = 0;
        if (page_list.value.length == 0) {
            let res: any = await GameEcpmlist()
            let sty: any = await getGames()
            gemas_list.value = sty
            page_list.value = res
            loading.value = false
            page_list.value.forEach((irem: any) => {
                cost_sum += irem.cost
                page_length.value = res
            })
            average.value = cost_sum;
            amount.value = cost_sum / page_list.value.length;
        }
        ecpm_list.value = []
        total.value = page_list.value.length
        page_list.value.sort((a, b) => new Date(a.event_time).getTime() - new Date(b.event_time).getTime());
        let totals_and = 0
        for (let index = 0; index < page_list.value.length; index++) {
            totals_and++
            if (index <= pageSize.value - 1) {
                if (and.value === 0) {
                    ecpm_list.value.push(page_list.value[index + length_size.value])
                } else {
                    if (total.value >= index + length_size.value * and.value + 1)
                        ecpm_list.value.push(page_list.value[index + length_size.value * and.value])
                }
            }
        }


        arrlist.value = []
        ecpm_list.value.forEach((item: any) => {
            let matchingGame = gemas_list.value.find(tiem => tiem.appid === item.appid);

            if (matchingGame && matchingGame.name) {
                // 使用可选链操作符确保安全访问
                item.name = matchingGame.name;
            } else {
                item.name = '该游戏没有名字';
            }
            // 确保 cost_sum 只在 item.cost 存在时才增加
            if (item.cost) {
                cost_sum += item.cost;
            }

            arrlist.value.push(item);
        });

        loading.value = false;
    } catch (error) {
        console.log('处理一条错误信息' + error);

    }

}
//数据更新
let updateexpm = async () => {
    loading.value = true
    page_list.value = []
    let res: any = await GameEcpmlist()
    page_list.value = res
    init()
}
//实时数据
let Realtime = () => {
    updateexpm()
    page_list.value = []
    arrlist.value = []
    value2.value = []
    amount.value = 0
    average.value = 0
    value1.value = []
    init()
    total.value = page_list.value.length
    pageSize.value = 10
}
//游戏查询

//游戏查询
let Game_Find = () => {
    pageSize.value = 10
    currentPage.value = 1
    and.value = 0
    length_size.value = 0

    if (value2.value.length == 0 && !value1.value) return
    loading.value = true
    let games_appid = value2.value;
    let times: Array<number> = [];
    if (!value1.value) {
        times = [-8.64e15, 8.64e15]
    } else {
        times[0] = new Date(value1.value[0]).getTime();
        times[1] = new Date(value1.value[1]).getTime();
    }
    let cost_sum = 0;
    let new_from_list: Array<any> = new Array<any>();

    page_length.value.forEach((item) => {
        if (isBetween(new Date(item.event_time).getTime(), times[0], times[1])) {
            if (games_appid.find(value => value === item.appid)) {
                if (item.cost) cost_sum += item.cost
                new_from_list.push(item)
            } else if (value2.value.length == 0) {
                new_from_list.push(item)
                if (item.cost) cost_sum += item.cost
            }

        } else if (games_appid.find(value => value === item.appid && value1.value.length == 0)) {
            new_from_list.push(item)
            if (item.cost) cost_sum += item.cost
        }

    })
    page_list.value = []
    page_list.value = new_from_list
    average.value = cost_sum;
    amount.value = cost_sum / page_list.value.length;
    if (page_list.value.length == 0) {
        value2.value = [];
        ElMessage.error('没有查询到此游戏数据，重置搜索');
        init()
    }
    init()

}
// 时期触发时间
let select_getitem = () => {
    console.log(1);

}
//时间查询
let find_getitem = (data: number) => {
    pageSize.value = 10
    and.value = 0
    length_size.value = 0
    currentPage.value = 1
    let today = new Date();
// 设置时间为凌晨0点
    today.setHours(0, 0, 0, 0);

// 获取昨天的日期
    let yesterday: any = new Date(today);
    let currentDateTime = new Date();

// 计算昨天的日期时间
    currentDateTime.setDate(currentDateTime.getDate());
    currentDateTime.setHours(23);
    currentDateTime.setMinutes(59);
    currentDateTime.setSeconds(0);

    // 格式化日期为中国时间格式
    let formattedDate = yesterday.toLocaleDateString('zh-CN');
    let res = new Date(formattedDate).getTime()
    // 输出格式化后的日期字符串
    value1.value[1] = currentDateTime;
    value1.value[0] = yesterday.setDate(today.getDate() - data);
    Game_Find()
}

//复制文本
let copy_appid = (date: string) => {
    replication(date)
}

//opendi 查询    
let arr_list = ref<Guers[]>([])


//数据重置
let resetting = async () => {

    location.reload();
}


//添加弹出框
const form = reactive<Guers>({
    aid: '',
    cost: undefined,
    did: '',
    event_name: '',
    event_time: '',
    open_id: '',
    id: undefined,
    appid: '',
    name: '',
})

const rules = reactive<FormRules<typeof form>>({
    //     aid: [{ validator: validatePass, trigger: 'blur' }],
    //     cost: [{ validator: validatePass2, trigger: 'blur' }],
    //     did: [{ validator: checkAge, trigger: 'blur' }],
    //     event_name: [{ validator: validatePass3, trigger: 'blur' }],
    //     event_time: [{ validator: validatePass4, trigger: 'blur' }],
    //     open_id: [{ validator: validatePass5, trigger: 'blur' }],
    //     id: [{ validator: validatePass6, trigger: 'blur' }],


})

const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            console.log('submit!')
            addlist()
            updateexpm()
        } else {
            console.log('error submit!')
        }
    })
}

// 添加游戏
// let addGame = () => {
//     dialogFormVisible.value = true
// }


let addlist = async () => {
    let res = await GameEcpmAdd([form])

}
//分页
const handleSizeChange = (val: number) => {
    and.value = val / 10
    pageSize.value = val
    init()
};

const handleCurrentChange = (val: number) => {
    let r = val * 10 - 10
    let i = val * 10
    length_size.value = r
    arrlist.value = []
    currentPage.value = val
    page_size.value = val * 10
    for (let index = 0; index < page_list.value.length; index++) {
        if (index + r + 1 <= page_size.value) {
            let res = index + r
            if (page_size.value <= total.value) {
                arrlist.value.push(page_list.value[res])
            } else if (res + 1 <= total.value) {
                arrlist.value.push(page_list.value[res])

            }

        }
    }
    init()
};

watch(value1, () => {
    if (value1.value == null || value1.value == undefined) {
        value1.value = []
    }

})

</script>


<style scoped>
.demonstration {
    margin-right: 10px;
}

.icon_color {
    color: #137DFB;
}
</style>